package many.redis.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;

@Configuration
public class RedisOneConfig {

    /**
     * redisOneTemplate 数据源
     */
    @Bean(name = "redisOneTemplate")
    public StringRedisTemplate redisOneTemplate(@Value("${spring.redis.one.host}") String host,
                                                @Value("${spring.redis.one.port}") int port,
                                                @Value("${spring.redis.one.database}") int index) {
        StringRedisTemplate temple = new StringRedisTemplate();
        temple.setConnectionFactory(connectionFactory(host, port, index));
        return temple;
    }

    /**
     * redisTwoTemplate 数据源
     */
    @Bean(name = "redisTwoTemplate")
    public StringRedisTemplate redisTwoTemplate(@Value("${spring.redis.two.host}") String host,
                                                @Value("${spring.redis.two.port}") int port,
                                                @Value("${spring.redis.two.database}") int index) {
        StringRedisTemplate temple = new StringRedisTemplate();
        temple.setConnectionFactory(connectionFactory(host, port, index));
        return temple;
    }

    /**
     * 无密码
     */
    public RedisConnectionFactory connectionFactory(String host,int port,int index) {
        JedisConnectionFactory jedis = new JedisConnectionFactory();
        jedis.setHostName(host);
        jedis.setPort(port);
        if (index != 0) {
            jedis.setDatabase(index);
        }
        jedis.afterPropertiesSet();
        return jedis;
    }

}
